var cache = require('../system/cache')
var common = require('../system/common')
var tools = require('../system/tools')
var wechat = require('../system/wechat')

var CK_ACCOUNT_LOGIN_FLAG = 'ck_account_login_flag'
var AUTH_CK_PREFIX = 'auth_cache_key_prefix_'

var privateObj = {
    isLogin: function () {
        try {
            var loginFlag = this.getUserInfo('token')
            return loginFlag
        } catch (e) {
            console.log('is login chk error')
            console.log(e)
        }
        return false
    },
    login: function (userToken) {
        try {
            this.setUserInfo('token', userToken)
            return true
            //return wx.setStorageSync(CK_ACCOUNT_LOGIN_FLAG, userToken)
        } catch (e) {
            console.log(e)
        }
        return false
    },
    setUserInfo: function (k, val) {
        var key = AUTH_CK_PREFIX + k     
        return cache.set(key, val)
    },
    getUserInfo: function (k) {
        var key = AUTH_CK_PREFIX + k 
        return cache.get(key)
    }
}
var auth = {
    getUserName: function () {
        return privateObj.getUserInfo('nickname')
    },
    getUserAvatar: function () {
        return privateObj.getUserInfo('avatar')
    },
    getUserGender: function () {
        var genderFlag = privateObj.getUserInfo('gender')
        return (genderFlag == 1) ? '男' : '女'
    },
    getUserId: function () {
        return privateObj.getUserInfo('token')
    },
    getUserBinded: function () {
        return privateObj.getUserInfo('binded')
    },
    getUserPhone: function () {
        return privateObj.getUserInfo('phone')
    },
    bindUser: function (userPhone, callback) {
        var userInfo = {
            open_id: this.getUserId(),
            app_user_photo: this.getUserAvatar(),
            nick_name: this.getUserName(),
            gender: this.getUserGender(),
            phone_no: userPhone,
        }
        tools.normalRequest({
            url: 'add_user',
            method: 'POST',
            data: userInfo,
            feedback: {
                success: function (data) {
                    privateObj.setUserInfo('binded', 1)
                    privateObj.setUserInfo('phone', userPhone)
                    callback()
                }
            }
        })
    },
    checkBind: function (feedback) {
        if (this.getUserBinded()) {
            return feedback.success()
        }
        tools.requestWithAuth({
          url: 'user_binded',
          feedback: {
            success: function (data) {
              if (data.binded) {
                  feedback.success()
              } else {
                  var currentPage = tools.getCurrentPageRoute()
                  wx.navigateTo({
                      url: '../bind/bind?resource_page=' + currentPage
                  })
              }
            }
          }
        })
    },
    checkUserDetail: function (needRefresh) {
        if (!privateObj.getUserInfo('detail') || needRefresh) {
            wx.getUserInfo({
                success: function (res) {
                    console.log(res)
                    var userDetail = res.userInfo
                    privateObj.setUserInfo('nickname', userDetail.nickName)
                    privateObj.setUserInfo('avatar', userDetail.avatarUrl)
                    privateObj.setUserInfo('gender', userDetail.gender)
                }
            })
            privateObj.setUserInfo('detail', 1)
        }
    },
    checkLogin: function (feedback) {
        var userToken = ''
        if (userToken = privateObj.isLogin()) {
            feedback.success({
                'token': userToken,
                'uid': userToken
            })
            return true
        }
        console.log('auth info is time out')
        this.login(feedback.success)
        return false
    },
    register: function () {
        wechat.call('getUserInfo', () => {
            wx.getUserInfo({
                success: res => {
                    //将用户信息提交给后台
                    tools.normalRequest({
                        url: '',
                        data: res.userInfo,
                        feedback: data => { }
                    })
                }
            })
        })
    },
    login: function(callback) {
        var that = this
        // 登录
        wx.login({
            success: res => {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                tools.normalRequest({
                    url: 'get_session_info',
                    data: {
                        code: res.code
                    },
                    feedback: {
                        success: data => {
                            console.log('login res:')
                            console.log(data)
                            if (privateObj.login(data.openid)) {
                                callback({})
                            }
                        }
                    }
                })
            },
            fail: res => {
                console.log(res)
            }
        })
    }
} 

module.exports = auth